package cn.zhoutingrui.pethome.config;

import cn.zhoutingrui.pethome.payload.Payload;
import cn.zhoutingrui.pethome.payload.PayloadData;
import cn.zhoutingrui.pethome.utils.JwtUtils;
import cn.zhoutingrui.pethome.utils.LoginContextUtils;
import cn.zhoutingrui.pethome.utils.RsaUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private String NO_LOGIN="{\"flag\":false,\"msg\":\"noLogin\"}";
    private String NO_MONEY="{\"flag\":false,\"msg\":\"noMoney\"}";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token!=null){
            //登录是否过期
           // Object o = LoginContextUtils.getLoginUser(request);
            Payload<PayloadData> payload = null;
            try {
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
                payload = JwtUtils.getInfoFromToken(token, publicKey, PayloadData.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (payload!=null){
                //重置时间
                //Payload payload= (Payload) o;
                //刷新token
                //过期时间
                Date expiration = payload.getExpiration();
                //刷新时间
                DateTime refreshTime = new DateTime(expiration).minusMinutes(5);
                //当前时间在刷新时间之后就要刷新一把
                if(refreshTime.isBefore(DateTime.now())){
                    //重新登录刷新toke
                    return fail(response,NO_LOGIN);
                }
                return true;
            }
        }
        return fail(response,NO_LOGIN);
    }

    private static boolean fail(HttpServletResponse response , String msg) throws IOException {
        //都是登录是吧返回一个错误 {“success”:false,"message":"noLogin"}，让前端条页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 在外面写好在拷贝进去
        writer.write(msg);
        writer.close();
        return false;
    }
}
